﻿using System;
using System.Data;
using BLL;
using Ext.Net;
using Roles;

namespace ERP.Modules
{
    public partial class Transaction : System.Web.UI.UserControl
    {
        private readonly Transaction_BLL clsTransaction = new Transaction_BLL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                CheckPermisstion();
                GetData();
                btnEdit.Disable(true);
                btnDel.Disable(true);
                btnExport.Disable(true);
                WindowsDestination();
                WindowsMethod();
            }
        }
        //-------Store-Datasource-----------------
        protected void StoreTransaction_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearch.Text = string.Empty;
            GetData();
        }
        //--------Buttom-Main------------------------
        protected void btnAddNew_Click(object sender, DirectEventArgs e)
        {
            GetComboBox();
            ClearTextBox();
            WindowsTransaction.Show();
        }
        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
            var sm = grTransaction.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    GetComboBox();
                    ClearTextBox();
                    DataDetail(int.Parse(row.RecordID));
                    WindowsTransaction.Show();
                    sm.UpdateSelection();
                }
        }

        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            var sm = grTransaction.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    try
                    {
                        Transaction_BLL.Deletetb_Transaction(int.Parse(row.RecordID));
                    }
                    catch (Exception)
                    {
                        HTML.clsFormat.Alert_ERROR("Thông Báo", "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                    }
                }
            GetData();
        }
        //--------Buttom-Popup------------------------
        protected void btnSavePopUp_Click(object sender, DirectEventArgs e)
        {
            if (txtTransaction_ID.Text == string.Empty)
            {
                InsertTransaction();
            }
            else
            {
                if (CheckPermisstionDobclick())
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", "Bạn không được cấp quyền để sửa đổi !");
                }
                else
                {
                    UpdateTransaction();
                }
            }
        }
        protected void btnCancelPopUp_Click(object sender, DirectEventArgs e)
        {
            WindowsTransaction.Close();
        }
        //----------Click-------------------
        protected void TransactionDblClick(object sender, DirectEventArgs e)
        {
            GetComboBox();
            ClearTextBox();
            int Transaction_ID = int.Parse(e.ExtraParams["Transaction_ID"]);
            DataDetail(Transaction_ID);
            WindowsTransaction.Show();
        }
        //----------Button-Windows---------------
        #region[Method]
        protected void GetData()
        {
            DataTable dtTransaction = clsTransaction.BindGirdtb_Transaction(string.Empty);
            if (dtTransaction != null && dtTransaction.Rows.Count > 0)
            {
                StoreTransaction.DataSource = dtTransaction;
                StoreTransaction.DataBind();
            }
        }
        protected void DataDetail(int id)
        {
            DataTable dtTransaction = clsTransaction.BindGirdtb_TransactionDetail(id);
            if (dtTransaction != null && dtTransaction.Rows.Count > 0)
            {
                txtTransaction_ID.Text = dtTransaction.Rows[0]["Transaction_ID"].ToString();
                txtTransaction_No.Text = dtTransaction.Rows[0]["Transaction_No"].ToString();
                txtCustomer_ID.Text = dtTransaction.Rows[0]["Customer_ID"].ToString();
                txtCustomer_Alias.Text = dtTransaction.Rows[0]["Customer_Alias"].ToString();
                txtCustomer_Name.Text = dtTransaction.Rows[0]["Customer_Name"].ToString();
                txtCustomer_Address.Text = dtTransaction.Rows[0]["Customer_Address"].ToString();
                txtCustomer_Tax_Code.Text = dtTransaction.Rows[0]["Customer_Contract_Tax_Code"].ToString();
                txtCustomer_Contact.Text = dtTransaction.Rows[0]["Contact_Name"].ToString();
                txtCustomer_Job.Text = dtTransaction.Rows[0]["Job_Name"].ToString();
                txtTransaction_Date.Text = dtTransaction.Rows[0]["Transaction_Date"].ToString();
                cbMethod.SetValue(int.Parse(dtTransaction.Rows[0]["Method_ID"].ToString()));
                cbDestination.SetValue(int.Parse(dtTransaction.Rows[0]["Destination_ID"].ToString()));
                txtTransaction_Content.Text = dtTransaction.Rows[0]["Transaction_Content"].ToString();
                txtTransaction_Result.Text = dtTransaction.Rows[0]["Transaction_Result"].ToString();
                txtTransaction_Note.Text = dtTransaction.Rows[0]["Transaction_Note"].ToString();
                rdbTransaction_Available_Content.Checked = dtTransaction.Rows[0]["Transaction_Available"].ToString() == "True";
                rdbTransaction_NotAvailable_Content.Checked = dtTransaction.Rows[0]["Transaction_NotAvailable"].ToString() == "True";
                rdbTransaction_Contact_Again_Content.Checked = dtTransaction.Rows[0]["Transaction_Contact_Again"].ToString() == "True";
                txtTransaction_Available_Content.Text = dtTransaction.Rows[0]["Transaction_Available_Content"].ToString();
                txtTransaction_NotAvailable_Content.Text = dtTransaction.Rows[0]["Transaction_NotAvailable_Content"].ToString();
                txtTransaction_Contact_Again_Content.Text = dtTransaction.Rows[0]["Transaction_Contact_Again_Content"].ToString();
                rdbTransaction_Potential.Checked = dtTransaction.Rows[0]["Transaction_Potential"].ToString() == "True";
                rdbTransaction_NotPotential.Checked = dtTransaction.Rows[0]["Transaction_NotPotential"].ToString() == "True";
                rdbTransaction_Unknown.Checked = dtTransaction.Rows[0]["Transaction_Unknown"].ToString() == "True";
            }
        }
        protected bool CheckInsert()
        {
            bool kiemtra = false;
            var Transaction = new Transaction_BLL();
            var dtTransaction = Transaction.BindGirdtb_Transaction(string.Empty);
            if (dtTransaction != null && dtTransaction.Rows.Count > 0)
            {
                foreach (DataRow dr in dtTransaction.Rows)
                {
                    if (txtTransaction_ID.Text != dr["Transaction_ID"].ToString())
                    {
                        if (txtTransaction_No.Text == dr["Transaction_No"].ToString())
                        {
                            kiemtra = true;
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Mã giao dịch đã tồn tại !");
                        }
                    }
                }
            }
            return kiemtra;
        }
        protected void InsertTransaction()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new ET.Transaction_ET
                    {
                        Transaction_No = txtTransaction_No.Text,
                        Customer_ID = int.Parse(txtCustomer_ID.Text),
                        Transaction_Date = DateTime.Parse(txtTransaction_Date.Text),
                        Method_ID = int.Parse(cbMethod.SelectedItem.Value),
                        Destination_ID = int.Parse(cbDestination.SelectedItem.Value),
                        Transaction_Content = txtTransaction_Content.Text,
                        Transaction_Result = txtTransaction_Result.Text,
                        Transaction_Note = txtTransaction_Note.Text,
                        Transaction_Available = rdbTransaction_Available_Content.Checked,
                        Transaction_NotAvailable = rdbTransaction_NotAvailable_Content.Checked,
                        Transaction_Contact_Again = rdbTransaction_Contact_Again_Content.Checked,
                        Transaction_Available_Content = rdbTransaction_Available_Content.Checked ? txtTransaction_Available_Content.Text : string.Empty,
                        Transaction_NotAvailable_Content = rdbTransaction_NotAvailable_Content.Checked ? txtTransaction_NotAvailable_Content.Text : string.Empty,
                        Transaction_Contact_Again_Content = rdbTransaction_Contact_Again_Content.Checked ? txtTransaction_Contact_Again_Content.Text : string.Empty,
                        Transaction_Schedule_ID = 0,
                        Transaction_Potential = rdbTransaction_Potential.Checked,
                        Transaction_NotPotential = rdbTransaction_NotPotential.Checked,
                        Transaction_Unknown = rdbTransaction_Unknown.Checked,
                        Transaction_Date_Add = DateTime.Now,
                        Transaction_Computer_Add = Environment.MachineName
                    };
                    Transaction_BLL.Inserttb_Transaction(obj);
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm mới thành công !");
                    GetData();
                    GetComboBox();
                    ClearTextBox();
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.ToString());
            }
        }
        protected void UpdateTransaction()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new ET.Transaction_ET
                    {
                        Transaction_ID = int.Parse(txtTransaction_ID.Text),
                        Transaction_No = txtTransaction_No.Text,
                        Customer_ID = int.Parse(txtCustomer_ID.Text),
                        Transaction_Date = DateTime.Parse(txtTransaction_Date.Text),
                        Method_ID = int.Parse(cbMethod.SelectedItem.Value),
                        Destination_ID = int.Parse(cbDestination.SelectedItem.Value),
                        Transaction_Content = txtTransaction_Content.Text,
                        Transaction_Result = txtTransaction_Result.Text,
                        Transaction_Note = txtTransaction_Note.Text,
                        Transaction_Available = rdbTransaction_Available_Content.Checked,
                        Transaction_NotAvailable = rdbTransaction_NotAvailable_Content.Checked,
                        Transaction_Contact_Again = rdbTransaction_Contact_Again_Content.Checked,
                        Transaction_Available_Content = rdbTransaction_Available_Content.Checked ? txtTransaction_Available_Content.Text : string.Empty,
                        Transaction_NotAvailable_Content = rdbTransaction_NotAvailable_Content.Checked ? txtTransaction_NotAvailable_Content.Text : string.Empty,
                        Transaction_Contact_Again_Content = rdbTransaction_Contact_Again_Content.Checked ? txtTransaction_Contact_Again_Content.Text : string.Empty,
                        Transaction_Schedule_ID = 0,
                        Transaction_Potential = rdbTransaction_Potential.Checked,
                        Transaction_NotPotential = rdbTransaction_NotPotential.Checked,
                        Transaction_Unknown = rdbTransaction_Unknown.Checked,
                        Transaction_Date_Modify = DateTime.Now,
                        Transaction_Computer_Modify = Environment.MachineName
                    };
                    Transaction_BLL.Updatetb_Transaction(obj);
                    WindowsTransaction.Close();
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Sữa thành công!");
                    GetData();
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.ToString());
            }
        }
        #endregion
        #region [ComboBox]
        protected void GetComboBox()
        {
            var clsDestination = new Destination_BLL();
            DataTable dtDestination = clsDestination.BindGirdtb_Destination(string.Empty);
            if (dtDestination != null && dtDestination.Rows.Count > 0)
            {
                DestinationStore.DataSource = dtDestination;
                DestinationStore.DataBind();
            }

            var clsMethod = new Method_BLL();
            DataTable dtMethod = clsMethod.BindGirdtb_Method(string.Empty);
            if (dtMethod != null && dtMethod.Rows.Count > 0)
            {
                MethodStore.DataSource = dtMethod;
                MethodStore.DataBind();
            }
        }
        protected void ReloadComboBox(object sender, StoreReadDataEventArgs e)
        {
            GetComboBox();
        }
        #endregion
        #region[ClearTextbox]
        protected void ClearTextBox()
        {
            FormPanelTransaction.Reset();
            txtTransaction_No.Text = MaTuDong();
            txtTransaction_Date.Text = DateTime.Now.ToShortDateString();
        }
        #endregion
        #region[MaTangTuDong]
        protected string MaTuDong()
        {
            int i;
            DataTable dt = clsTransaction.BindGirdtb_Transaction(string.Empty);
            if (dt != null && dt.Rows.Count > 0)
            {
                int max = int.Parse(dt.Rows[0]["Transaction_ID"].ToString());
                for (i = 0; i < dt.Rows.Count; i++)
                {
                    if (int.Parse(dt.Rows[i]["Transaction_ID"].ToString()) > max)
                    {
                        max = int.Parse(dt.Rows[i]["Transaction_ID"].ToString());
                    }
                }
                i = max + 1;
            }
            else
            {
                i = 0;
            }
            return "GD_00" + i;
        }
        #endregion
        #region[Search]
        protected void Search_Event(object sender, DirectEventArgs e)
        {
            DataTable dtTransaction = clsTransaction.BindGirdtb_Transaction(txtSearch.Text);
            if (dtTransaction != null && dtTransaction.Rows.Count > 0)
            {
                StoreTransaction.DataSource = dtTransaction;
                StoreTransaction.DataBind();
            }
        }
        #endregion

        protected void rdbTransaction_Contact_Again_Content_Click(object sender, DirectEventArgs e)
        {
            if (rdbTransaction_Available_Content.Checked)
            {
                txtTransaction_Available_Content.Disabled = false;
                txtTransaction_Available_Content.AllowBlank = false;
                txtTransaction_NotAvailable_Content.Disabled = true;
                txtTransaction_Contact_Again_Content.Disabled = true;
            }
            else if (rdbTransaction_NotAvailable_Content.Checked)
            {
                txtTransaction_NotAvailable_Content.Disabled = false;
                txtTransaction_NotAvailable_Content.AllowBlank = false;
                txtTransaction_Available_Content.Disabled = true;
                txtTransaction_Contact_Again_Content.Disabled = true;
            }
            else
            {
                txtTransaction_Contact_Again_Content.Disabled = false;
                txtTransaction_Contact_Again_Content.AllowBlank = false;
                txtTransaction_NotAvailable_Content.Disabled = true;
                txtTransaction_Available_Content.Disabled = true;
            }
        }
        #region[Permisstion]
        private void CheckPermisstion()
        {
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Transaction, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnAdd == false)
                {
                    btnAddNew.Visible = false;
                }
                if (Is_BtnEdit == false)
                {
                    btnEdit.Visible = false;
                }
                if (Is_BtnView == false)
                {
                    PanelTransaction.Visible = false;
                }
                if (Is_BtnDel == false)
                {
                    btnDel.Visible = false;
                }
                if (Is_BtnPrint == false)
                {
                    btnExport.Visible = false;
                }
            }
        }
        private bool CheckPermisstionDobclick()
        {
            var check = false;
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Transaction, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnEdit == false)
                {
                    check = true;
                }
            }
            return check;
        }
        #endregion
        #region Customer
        protected void GetCustomer()
        {
            var clsCustomer = new Customer_BLL();
            DataTable dtCustomer = clsCustomer.BindGirdtb_Customer(txtSearchTransactionCustomer.Text);
            if (dtCustomer != null && dtCustomer.Rows.Count > 0)
            {
                StoreTransactionCustomer.DataSource = dtCustomer;
                StoreTransactionCustomer.DataBind();
            }
            else
            {
                grTransactionCustomer.GetStore().RemoveAll();
            }
        }
        protected void btnCustomer_Click(object sender, DirectEventArgs e)
        {
            GetCustomer();
            WindowTransactionCustomer.Show();
        }
        protected void StoreTransactionCustomer_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            StoreTransactionCustomer.Reload();
        }

        protected void CellTransactionCustomer_Click(object sender, DirectEventArgs e)
        {
            var sm = grTransactionCustomer.GetSelectionModel() as CellSelectionModel;
            if (sm != null)
            {
                string id = sm.SelectedCell.RecordID;
                var clsCustomer = new Customer_BLL();
                DataTable dtCustomer = clsCustomer.GetCustomerDetail(int.Parse(id));
                txtCustomer_ID.Text = dtCustomer.Rows[0]["Customer_ID"].ToString();
                txtCustomer_Alias.Text = dtCustomer.Rows[0]["Customer_Alias"].ToString();
                txtCustomer_Name.Text = dtCustomer.Rows[0]["Customer_Name"].ToString();
                txtCustomer_Address.Text = dtCustomer.Rows[0]["Customer_Address"].ToString();
                txtCustomer_Contact.Text = dtCustomer.Rows[0]["Contact_Name"].ToString();
                txtCustomer_Job.Text = dtCustomer.Rows[0]["Job_Name"].ToString();
                sm.Clear();
                sm.UpdateSelection();
                WindowTransactionCustomer.Close();
            }
        }
        protected void SearchTransactionCustomer_Event(object sender, DirectEventArgs e)
        {
            GetCustomer();
        }
        #endregion

        private void WindowsDestination()
        {
            Window win = new Window()
            {
                ID = "WindowsDestination",
                Title = "Mục đích",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/Destination.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
        private void WindowsMethod()
        {
            Window win = new Window()
            {
                ID = "WindowsMethod",
                Title = "Phương thức",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/Method.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
    }
}